<?php
namespace Institution\Controller\Component;

use ArrayObject;
use Cake\ORM\TableRegistry;
use Cake\Controller\Component;
use Cake\Event\Event;

use Cake\Utility\Exception\XmlException;
use DOMDocument;
use Exception;
use DOMNode;
use DOMText;
use SimpleXMLElement;

class CreateUsersComponent extends Component
{
    public function getUniqueOpenemisId()
    {
        $openemisId = TableRegistry::get('User.Users')->getUniqueOpenemisId();
        $openemis = ['openemis_no' => $openemisId];
        return json_encode($openemis);
    }

    public function getAutoGeneratedPassword()
    {
        $ConfigItems = TableRegistry::get('Configuration.ConfigItems');
        $password = ['password' => $ConfigItems->getAutoGeneratedPassword()];
        return json_encode($password);
    }
    /**
     * Get response for User Data from CSPD api
     * @author Anubhav Jain <anubhav.jain@mail.valuecoders.com>
     * @author Dr Khindol Madraimov <khindol.madraimov@gmail.com>
     * @return array
     * @ticket POCOR-6930, POCOR-7916
     **/
    public function getResponseForCspd($soapUrl, $soapUser, $soapPassword, $xml_post_string, $soapAction = "http://tempuri.org/IVitalEvents/gePersonal")
    {
        $headers = array(
            "Accept: application/soap+xml",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "Content-length: ".strlen($xml_post_string),
        ); //SOAPAction: your op URL
        if($soapAction == "http://tempuri.org/IVitalEvents/gePersonal"){
            $headers[] = "Content-Type: application/xml";
            $headers[] = "soapAction: http://tempuri.org/IVitalEvents/gePersonal";
        }
        if($soapAction == "http://tempuri.org/IVitalEvents/getPersonalByName"){
            $headers[] = "Content-Type: text/xml; charset=utf-8";
            $headers[] = "soapAction: http://tempuri.org/IVitalEvents/getPersonalByName";
        }
//        $this->log($headers, 'debug');
        $url = $soapUrl;
        // PHP cURL  for https connection with auth
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // converting
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * Get xml data to array
     * @author Anubhav Jain <anubhav.jain@mail.valuecoders.com>
     * @return array
     * @ticket POCOR-6930
     **/
    public function XMLtoArray($xml) {
        $previous_value = libxml_use_internal_errors(true);
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->preserveWhiteSpace = false;
        $dom->loadXml($xml);
        libxml_use_internal_errors($previous_value);
        if (libxml_get_errors()) {
            return [];
        }
        return $this->DOMtoArray($dom);
    }
    /**
     * Get DOM to array
     * @author Anubhav Jain <anubhav.jain@mail.valuecoders.com>
     * @return array
     * @ticket POCOR-6930
     **/
    public function DOMtoArray($root) {
        $result = array();
        if ($root->hasAttributes()) {
            $attrs = $root->attributes;
            foreach ($attrs as $attr) {
                $result['@attributes'][$attr->name] = $attr->value;
            }
        }
        if ($root->hasChildNodes()) {
            $children = $root->childNodes;
            if ($children->length == 1) {
                $child = $children->item(0);
                if (in_array($child->nodeType,[XML_TEXT_NODE,XML_CDATA_SECTION_NODE])) {
                    $result['_value'] = $child->nodeValue;
                    return count($result) == 1
                        ? $result['_value']
                        : $result;
                }
            }
            $groups = array();
            foreach ($children as $child) {
                if (!isset($result[$child->nodeName])) {
                    $result[$child->nodeName] = $this->DOMtoArray($child);
                } else {
                    if (!isset($groups[$child->nodeName])) {
                        $result[$child->nodeName] = array($result[$child->nodeName]);
                        $groups[$child->nodeName] = 1;
                    }
                    $result[$child->nodeName][] = $this->DOMtoArray($child);
                }
            }
        }
        return $result;
    }
}
